package cn.com.cmbc.controller;

import cn.com.cmbc.service.FileService;
import cn.com.cmbc.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class FileController {
    private static final Logger LOG = LoggerFactory.getLogger(FileController.class);

    private FileService fileService = new FileService();

    @GetMapping("/getfiles")
    public String getFiles(@RequestParam String path) {
//        return "yes!!!";
        if (path == null || path.isEmpty()) {
            path = FileUtil.DEFAULT_PATH;
            LOG.info("使用默认读取路径");
        }

        Path filePath = Paths.get(path);
        if (!Files.exists(filePath) || !Files.isDirectory(filePath)) {
            LOG.error("无效的路径或不是目录: {}", path);
            throw new IllegalArgumentException("无效的路径或不是目录: " + path);
        }

        LOG.info("路径读取成功：{}", path);

        String pathFileJSON = fileService.getPathFileJSON(path);

        LOG.info("获取到的文件列表：{}\n", pathFileJSON);
        // 返回JSON格式的响应
        return String.format("{\"status\":\"success\",\"message\":%s}", pathFileJSON);
    }

}
